import { getOssToken } from "@/api/system";
import request from "@/request";
import { ElLoading } from "element-plus";

export const getFile = (accept = "image/*") => {
  return new Promise((resolve) => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = accept;
    fileInput.className = "hidden_input";
    fileInput.onchange = (e) => {
      resolve(e.target.files[0]);
    };
    fileInput.click();
    setTimeout(() => {
      fileInput.remove();
    });
  });
};

export const file2Blob = (file) => {
  return new Promise((resolve) => {
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function (event) {
      let blob = new Blob([event.target.result], { type: file.type });
      resolve(blob);
    };
  });
};

const getOssData = async (file) => {
  const blobFile = await file2Blob(file);
  const { data } = await getOssToken();
  return {
    ossData: {
      OSSAccessKeyId: data.accessKeyId,
      policy: data.policy,
      signature: data.signature,
      host: data.url,
      dir: data.randomFileName,
      fileName: file.name,
      key: `${data.randomFileName}/${file.name}`,
      file: blobFile,
    },
    url: data.url,
  };
};

export const apiUpload = async (file) => {
  const blobFile = await file2Blob(file);
  const formData = new FormData();
  formData.append("file", blobFile, file.name);
  let data = null;
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  try {
    const res = await request({
      url: "/oss/minio/upload",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    data = res?.data;
  } finally {
    loading.close();
  }

  return {
    fileSize: file.size,
    originalFilename: data.originalFileName,
    url: data.url,
    name: data.originalFileName,
  };
};

export const ossUpload = async (file) => {
  // 获取oss配置
  const { ossData, url: uploadUrl } = await getOssData(file);
  // 装配formData
  const formData = new FormData();
  Object.entries(ossData).forEach(([key, value]) => {
    formData.append(key, value);
  });
  const responseStatus = await request({
    url: uploadUrl,
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (responseStatus === 204) {
    const { host, key, fileName } = ossData;
    return {
      fileName: key,
      fileSize: file.size,
      originalFilename: fileName,
      url: `${host}${key}`,
      name: fileName,
    };
  }
  return null;
};

export const transformSize = (size) => {
  if (size > 1024 * 1024) {
    return `${(size / 1024 / 1024).toFixed(2)}M`;
  } else if (size > 1024) {
    return `${(size / 1024).toFixed(2)}K`;
  } else {
    return `${size}KB`;
  }
};

export const copyToClipBoard = async (content) => {
  if (navigator.clipboard) {
    try {
      await navigator.clipboard.writeText(content);
      ElMessage.success("复制成功");
    } catch (e) {
      ElMessage.success("复制失败");
    }
  } else if (window.clipboardData && window.clipboardData.setData) {
    window.clipboardData.setData("Text", content);
    ElMessage.success("复制成功");
  }
};

export const toggleHtmlScroll = () => {
  const html = document.getElementsByTagName("html")[0];
  if (!html.style.overflow) {
    html.style.overflow = "hidden";
  } else {
    html.style.overflow = null;
  }
};

export const download = async (fileName, fileUrl) => {
  const stream = await request({
    url: fileUrl,
    method: "get",
    responseType: "blob",
  });

  const a = document.createElement("a");
  a.href = URL.createObjectURL(stream.data);
  a.download = fileName;
  a.click();
};
